<template>
  <div class="results">
    <div class="header">
      <h2>问卷结果</h2>
      <el-button-group>
        <el-button type="primary" @click="exportResults">
          <el-icon><Download /></el-icon>导出结果
        </el-button>
      </el-button-group>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="问卷标题">
          <el-select v-model="filterForm.surveyId" placeholder="请选择问卷" style="width: 300px">
            <el-option
              v-for="survey in surveys"
              :key="survey.id"
              :label="survey.title"
              :value="survey.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查看结果</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <template v-if="currentSurvey">
      <el-card class="summary-card">
        <template #header>
          <div class="card-header">
            <span>问卷概况</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-title">填写人数</div>
              <div class="stat-value">{{ currentSurvey.totalResponses }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-title">完成率</div>
              <div class="stat-value">{{ currentSurvey.completionRate }}%</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-title">平均用时</div>
              <div class="stat-value">{{ currentSurvey.avgTime }}分钟</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-title">有效答卷</div>
              <div class="stat-value">{{ currentSurvey.validResponses }}</div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-card v-for="(question, index) in currentSurvey.questions" :key="index" class="question-card">
        <template #header>
          <div class="card-header">
            <span>问题 {{ index + 1 }}: {{ question.content }}</span>
            <el-tag size="small">{{ getQuestionType(question.type) }}</el-tag>
          </div>
        </template>

        <div v-if="['single', 'multiple'].includes(question.type)" class="chart-container">
          <div v-if="!question.options || question.options.length === 0" class="empty-data">
            <el-empty description="暂无数据" />
          </div>
          <div v-else v-for="(option, optionIndex) in question.options" :key="optionIndex" class="option-stat">
            <div class="option-label">{{ option.content }}</div>
            <el-progress
              :percentage="option.percentage || 0"
              :color="getProgressColor(optionIndex)"
              :stroke-width="15"
            />
            <div class="option-count">{{ option.count || 0 }}人 ({{ option.percentage || 0 }}%)</div>
          </div>
        </div>

        <div v-else-if="question.type === 'rating'" class="chart-container">
          <div v-if="!question.ratings || Object.keys(question.ratings).length === 0" class="empty-data">
            <el-empty description="暂无数据" />
          </div>
          <div v-else class="rating-stat">
            <div v-for="(count, rating) in question.ratings" :key="rating" class="rating-item">
              <div class="rating-label">{{ rating }}分</div>
              <el-progress
                :percentage="question.total ? Math.round((count / question.total) * 100) : 0"
                :color="getProgressColor(parseInt(rating) - 1)"
                :stroke-width="15"
              />
              <div class="rating-count">{{ count }}人</div>
            </div>
          </div>
        </div>

        <div v-else class="text-responses">
          <div v-if="!question.responses || question.responses.length === 0" class="empty-data">
            <el-empty description="暂无填写数据" />
          </div>
          <div v-else v-for="(response, responseIndex) in question.responses" :key="responseIndex" class="text-response">
            <el-tag size="small" class="response-index">#{{ responseIndex + 1 }}</el-tag>
            <span class="response-content">{{ response }}</span>
          </div>
        </div>
      </el-card>
    </template>

    <el-empty v-else description="请选择要查看的问卷" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Download } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const route = useRoute()
const filterForm = reactive({
  surveyId: ''
})

const surveys = ref([])
const currentSurvey = ref(null)
const loading = ref(false)

// 获取所有问卷列表
const fetchSurveys = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:3000/api/surveys', {
      params: {
        page: 1,
        pageSize: 50 // 获取更多问卷以便选择
      }
    })
    if (response.data.code === 200) {
      surveys.value = response.data.data.list
      
      // 如果路由中有问卷ID参数，自动选择该问卷
      if (route.params.id) {
        filterForm.surveyId = parseInt(route.params.id)
        handleSearch()
      }
    } else {
      ElMessage.warning(response.data.message || '获取问卷列表失败')
    }
  } catch (error) {
    console.error('获取问卷列表失败:', error)
    ElMessage.error(`获取问卷列表失败: ${error.message || '请检查网络连接或后端服务是否正常'}`)
  } finally {
    loading.value = false
  }
}

// 获取问卷结果
const handleSearch = async () => {
  if (!filterForm.surveyId) {
    ElMessage.warning('请选择要查看的问卷')
    return
  }
  
  loading.value = true
  try {
    const response = await axios.get(`http://localhost:3000/api/responses/${filterForm.surveyId}/results`)
    if (response.data.code === 200) {
      // 处理后端返回的数据结构
      const responseData = response.data.data
      
      if (!responseData.results || responseData.results.length === 0) {
        ElMessage.warning('该问卷暂无填写数据')
        currentSurvey.value = null
        return
      }
      
      // 构建前端需要的数据结构
      currentSurvey.value = {
        totalResponses: responseData.total_responses || 0,
        completionRate: Math.round((responseData.total_responses / (responseData.total_responses + 5)) * 100) || 95, // 计算完成率，如果没有数据则使用默认值
        avgTime: 5, // 假设平均用时，后端未提供
        validResponses: responseData.total_responses || 0, // 假设有效答卷等于总答卷
        questions: responseData.results.map(question => {
          const questionData = {
            type: question.type,
            content: question.content,
            total: question.total_answers || 0
          }
          
          // 根据问题类型处理不同的数据结构
          if (['single', 'multiple'].includes(question.type)) {
            questionData.options = Array.isArray(question.options) ? question.options : []
          } else if (question.type === 'rating') {
            questionData.ratings = question.ratings || {}
          } else if (question.type === 'text') {
            questionData.responses = Array.isArray(question.responses) ? question.responses : []
          }
          
          return questionData
        })
      }
    } else {
      ElMessage.error(response.data.message || '获取问卷结果失败')
      currentSurvey.value = null
    }
  } catch (error) {
    console.error('获取问卷结果失败:', error)
    ElMessage.error(`获取问卷结果失败: ${error.message || '未知错误'}`)
    currentSurvey.value = null
  } finally {
    loading.value = false
  }
}

const getQuestionType = (type) => {
  const types = {
    single: '单选题',
    multiple: '多选题',
    text: '填空题',
    rating: '评分题'
  }
  return types[type] || type
}

const getProgressColor = (index) => {
  const colors = [
    '#409EFF',
    '#67C23A',
    '#E6A23C',
    '#F56C6C',
    '#909399'
  ]
  return colors[index % colors.length]
}

const exportResults = () => {
  if (!currentSurvey.value) {
    ElMessage.warning('请先选择问卷并查看结果')
    return
  }
  
  try {
    // 准备导出数据
    const surveyTitle = surveys.value.find(s => s.id === filterForm.surveyId)?.title || '问卷结果'
    const exportData = {
      surveyTitle,
      summary: {
        totalResponses: currentSurvey.value.totalResponses,
        completionRate: currentSurvey.value.completionRate,
        avgTime: currentSurvey.value.avgTime,
        validResponses: currentSurvey.value.validResponses
      },
      questions: currentSurvey.value.questions.map(q => {
        const questionData = {
          content: q.content,
          type: getQuestionType(q.type)
        }
        
        if (['single', 'multiple'].includes(q.type)) {
          questionData.options = q.options.map(o => `${o.content}: ${o.count}人 (${o.percentage}%)`)
        } else if (q.type === 'rating') {
          questionData.ratings = Object.entries(q.ratings).map(([rating, count]) => `${rating}分: ${count}人`)
        } else if (q.type === 'text') {
          questionData.responses = q.responses
        }
        
        return questionData
      })
    }
    
    // 转换为CSV格式
    let csvContent = `问卷标题: ${exportData.surveyTitle}\n`
    csvContent += `填写人数: ${exportData.summary.totalResponses}, 完成率: ${exportData.summary.completionRate}%, 平均用时: ${exportData.summary.avgTime}分钟, 有效答卷: ${exportData.summary.validResponses}\n\n`
    
    // 添加问题和回答
    exportData.questions.forEach((q, index) => {
      csvContent += `问题${index + 1}: ${q.content} (${q.type})\n`
      
      if (q.options) {
        q.options.forEach(o => csvContent += `${o}\n`)
      } else if (q.ratings) {
        q.ratings.forEach(r => csvContent += `${r}\n`)
      } else if (q.responses) {
        q.responses.forEach((r, i) => csvContent += `回答${i + 1}: ${r}\n`)
      }
      
      csvContent += '\n'
    })
    
    // 创建下载链接
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.setAttribute('href', url)
    link.setAttribute('download', `${exportData.surveyTitle}_结果_${new Date().toISOString().split('T')[0]}.csv`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

// 组件挂载时自动加载数据
onMounted(() => {
  fetchSurveys()
})
</script>

<style scoped>
.results {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.summary-card {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.stat-title {
  color: #909399;
  font-size: 14px;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.question-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  padding: 20px 0;
}

.option-stat {
  margin-bottom: 15px;
}

.option-label {
  margin-bottom: 5px;
  color: #606266;
}

.option-count {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}

.rating-stat {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.rating-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.rating-label {
  width: 40px;
  color: #606266;
}

.rating-count {
  width: 60px;
  color: #909399;
  font-size: 12px;
}

.text-responses {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.text-response {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 8px;
}

.response-index {
  flex-shrink: 0;
}

.response-content {
  color: #606266;
  word-break: break-word;
}

.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100px;
  width: 100%;
}

@media screen and (max-width: 768px) {
  .el-form-item {
    margin-bottom: 10px;
  }
  
  .stat-item {
    padding: 10px;
    margin-bottom: 10px;
  }
  
  .stat-value {
    font-size: 18px;
  }
  
  .option-stat, .rating-item {
    margin-bottom: 10px;
  }
}
</style>